package cn.lecosa.util;

import com.typesafe.config.Config;
import com.typesafe.config.ConfigFactory;
import org.apache.log4j.Logger;

import java.sql.*;

public class JdbcUtils {

    private static Logger log = Logger.getLogger(JdbcUtils.class);
    public static String url = null;
    public static String user = null;
    public static String password = null;
    public static String driver = null;
    /** 加载Resouces目录下配置文件*/
    static{
        try {
            Config config  = ConfigFactory.load();
            url = config.getString("db.default.url");
            user = config.getString("db.default.user");
            password = config.getString("db.default.password");
            driver = config.getString("db.default.driver");
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    //获取数据库链接
    public static Connection getConn() throws Exception {
        log.info("**************************************Mysql连接信息:");
        log.info(url);log.info(user);log.info(password);log.info(driver);
        boolean driverLoad = false; //驱动类是否加载
        if(!driverLoad){
            Class.forName(driver);
            driverLoad = true;
        }
        return DriverManager.getConnection(url, user, password);

    }

    //释放资源
    public static void release(Connection conn,PreparedStatement pst,ResultSet rs){
        if(conn != null){
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if(pst != null){
            try {
                pst.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if(rs != null){
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }


}